define(['knockout',
    'platform.common',
    'bootbox',
    'knockout-bsTable',
    'knockout-jsTree',
    'knockout-component',
    'bootstrapValidator',
    'bootstrapValidator-zhCN',
    'sco.msg'], function (ko, platform, bootbox) {
    var rest = {
        get: function (id) {//根据主键获取信息
            var param = {};
            param.org_id = id;
            return platform.servicebreak('~/rest/org/selectOne', param).responseJSON;
        },
        remove: function (id) {//根据主键删除信息
            var param = {};
            param.org_id = id;
            platform.servicebreakAsync('~/rest/org/delete', param, 'post')
                .done(function (response) {
                    if (response instanceof Object && response.meta.success) {
                        platform.showOperTip('DELSUC');
                        viewModel.tableViewModel.refresh();
                        viewModel.refreshTree();
                    } else {
                        platform.showErrorTip(response.meta.message);
                    }
                });
        },
        save: function (param) {//保存信息
            platform.servicebreakAsync('~/rest/org/save', param, 'post',
                function () {
                    platform.showOperTip('dealing');
                }).done(function (response) {
                if (response instanceof Object && response.meta.success) {
                    platform.showOperTip('savesuc');
                    viewModel.tableViewModel.refresh();
                    viewModel.refreshTree();
                }
            });
        },
        update: function (param) {//部分字段更新
            platform.servicebreakAsync('~/rest/org/changeMenuPid', param,
                'post', function () {
                    platform.showOperTip('dealing');
                }).done(function (response) {
                var result = response.responseJSON;
                if (result instanceof Object && result.meta.success) {
                    platform.showOperTip('savesuc');
                    viewModel.tableViewModel.refresh();
                    viewModel.refreshTree();
                }

            });
        },
        loadTreeNodes: function () {
            return platform.servicebreak('~/rest/org/getTreeNodes', {nodeId: ''}).responseJSON;
        }
    };

    var kbTable = require('knockout-bsTable');
    var jsTree = require('knockout-jsTree');


    var orgLevelGroup = platform.getPubCode('83785d86-aaab-4567-901e-f8291a76e036').responseObject;
    var orgTypeGroup = platform.getPubCode('018f6604-6e5a-4011-9ba6-75f0c868920e').responseObject;

    var ViewModel = function () {
        var self = this;

        self.selectedNode = ko.observable();
        self.treeViewModel = new jsTree.jsTreeViewModel({
            core: {
                data: {
                    url: platform.mapUrl('~/rest/org/getTreeNodes?lazy'),
                    data: function (node) {
                        return JSON.stringify({'nodeId': node.id});
                    },
                    contentType: 'application/json',
                    dataType: 'json',
                    method: 'post'
                },
                types: {'default': {'icon': 'fa fa-bank'}},

            },
            plugins: ['wholerow']
        });
        self.onTreeNodeSelected = function (event, data) {
            var param = {};
            if (data.node.parent == '#') {
                param.p_org_id = '';
                self.selectedNode('');
            } else {
                param.p_org_id = data.node.id;
                self.selectedNode(data.node.id);
            }
            self.tableViewModel.refresh(param);
        };
        self.columns = [{
            checkbox: true,
            align: 'center',
            width: 30
        }, {
            field: 'display_order',
            title: '序号',
            formatter: function (value, row, index) {
                var options = self.tableViewModel.getOptions();
                var indexPageNum = parseInt(options.pageNumber);
                var indexPageSize = parseInt(options.pageSize);
                return ((indexPageNum - 1) * indexPageSize)
                    + (index + 1);
            },
            width: 35,
            align: 'center'
        }, {
            field: 'org_id',
            title: '主键标识',
            visible: false
        }, {
            field: 'org_name',
            title: '组织机构名称',
            width: 120,
            align: 'center'
        }, {
            field: 'org_code',
            title: '组织机构编码',
            width: 120,
            align: 'center'
        }, {
            field: 'org_type',
            title: '组织机构类型',
            width: 120,
            align: 'center',
            formatter: function (value, row, index) {
                var showText;
                $.each(orgTypeGroup, function (index, node) {
                    if (node.code_value === value) {
                        showText = node.code_text;
                    }
                });
                return showText;
            }
        }];
        self.tableViewModel = new kbTable.bootstrapTableViewModel({
            url: platform.mapUrl('~/rest/org/list'),
            toolbar: '#toolbar',
            queryParams: function (params) {
                return {
                    pageNumber: params.offset / params.limit + 1,
                    pageSize: params.limit,
                    p_org_id: ''
                };
            },
            columns: self.columns
        });
        self.modalVisible = ko.observable(false);
        self.orgViewModel = {
            title: ko.observable(null),
            orgId: ko.observable(null),
            orgCode: ko.observable(null),
            orgName: ko.observable(null),
            orgType: ko.observable(null),
            orgTypeGroup: ko.computed(function () {
                // return platform.getPubCode('018f6604-6e5a-4011-9ba6-75f0c868920e').responseObject;
                return orgTypeGroup;
            }, self),
            orgLevel: ko.observable(null),
            orgLevelGroup: ko.computed(function () {
                // return platform.getPubCode('83785d86-aaab-4567-901e-f8291a76e036').responseObject;
                return orgLevelGroup;
            }, self),
            pOrgId: ko.observable(null),
            enabled: ko.observable(true),
            editStatus: ko.observable(),
            recordStatus: ko.observable(),

            resetForm: function () {//重置表单
                $('#detailForm').resetForm();
                if ($('#detailForm').data('bootstrapValidator') != null ||
                    $('#detailForm').data('bootstrapValidator') != undefined) {
                    $('#detailForm').data('bootstrapValidator').resetForm();
                }
                this.orgId('');
                this.orgCode('');
                this.orgName('');
                this.orgType('');
                this.orgLevel('');
                this.editStatus('0');
                this.recordStatus('1');
            },
            disableForm: function () {//禁用元件编辑
                $('#detailForm').find('input,textarea,select').attr('disabled', true);
            },
            enableForm: function () {//启用元件编辑
                $('#detailForm').find('input,textarea,select').attr('disabled', false);
            },
            setFormData: function (id) {//设置表单数据
                var result = rest.get(id);
                if (result instanceof Object && result.meta.success) {
                    var info = result.responseObject;

                    this.orgId(info.org_id);
                    this.orgName(info.org_name);
                    this.orgCode(info.org_code);
                    this.orgLevel(info.org_level);
                    this.orgType(info.org_type);
                    this.recordStatus(info.record_status);
                }
            },
            validateForm: function () {//启用表单校验
                $('#detailForm').bootstrapValidator({
                    message: 'This value is not valid',
                    feedbackIcons: {
                        valid: 'fa fa-ok',
                        invalid: 'fa fa-remove',
                        validating: 'fa fa-refresh'
                    },
                    excluded: [':disabled'],
                    fields: {
                        orgCode: {
                            validators: {
                                notEmpty: {
                                    message: '*组织机构编码为必填字段!'
                                },
                                stringLength: {
                                    min: 1,
                                    max: 50,
                                    message: '组织机构编码长度最多不超出50个字符!'
                                }
                            }
                        },
                        orgName: {
                            validators: {
                                notEmpty: {
                                    message: '*组织机构名称为必填字段!'
                                },
                                stringLength: {
                                    min: 0,
                                    max: 128,
                                    message: '组织机构名称长度最多不超出128个字符!'
                                }
                            }
                        }
                    }
                });
            },
            showNewForm: function (id) {//新增表单
                this.resetForm();
                this.validateForm();
                this.enableForm();

                this.title('新增组织机构信息');
                this.orgId(platform.uuid());
                if (id === undefined) {
                    this.pOrgId('');
                } else {
                    this.pOrgId(id);
                }
                this.editStatus('0');
                this.enabled(true);
                self.modalVisible(true);
            },
            showEditForm: function (id) {//编辑表单
                this.resetForm();
                this.validateForm();
                this.setFormData(id);
                this.enableForm();

                this.title('编辑组织机构信息');
                this.editStatus('1');
                this.enabled(true);
                self.modalVisible(true);
            },
            showViewForm: function (id) {//查看表单
                this.resetForm();
                this.disableForm();
                this.setFormData(id);
                this.title('查看组织机构信息');
                this.enabled(false);
                self.modalVisible(true);
            },
            save: function () {//保存
                $('#detailForm').data('bootstrapValidator').validate();
                if (!$('#detailForm').data('bootstrapValidator').isValid()) {
                    platform.showOperTip('VALIDATEFAIL');
                    return;
                }
                var param = {};
                param.org_id = this.orgId();
                param.org_code = this.orgCode();
                param.org_name = this.orgName();
                param.org_level = this.orgLevel();
                param.org_type = this.orgType();
                param.edit_status = this.editStatus();

                if (this.editStatus() === '0') {
                    param.p_org_id = this.pOrgId();
                    param.record_status = this.recordStatus();
                } else if (this.editStatus() === '1') {
                    param.record_status = this.recordStatus();
                }
                rest.save(param);
            },
            close: function () {//关闭
                self.modalVisible(false);
                $('#orgDialog').toggleClass('hide');
            }
        };
        self.fnAdd = function () {//新增操作
            if (self.selectedNode() == null) {
                bootbox.confirm({
                    title: '<i class="fa fa-warning"></i>&nbsp;&nbsp;系统提示',
                    size: 'small',
                    message: '确认是否新增顶级组织机构单元?',
                    buttons: {
                        confirm: {
                            label: '确认',
                            className: 'btn-success btn-sm'
                        },
                        cancel: {
                            label: '取消',
                            className: 'btn-default btn-sm'
                        }
                    },
                    callback: function (result) {
                        if (result) {
                            self.orgViewModel.showNewForm();
                            $('#orgDialog').toggleClass('hide');
                        }
                    }
                });
            } else {
                self.orgViewModel.showNewForm(self.selectedNode());
                $('#orgDialog').toggleClass('hide');
            }

        };
        self.fnEdit = function () {//修改操作
            var selections = self.tableViewModel.getSelections();
            if (selections.length === 1) {
                var id = selections[0].org_id;
                self.orgViewModel.showEditForm(id);
                $('#orgDialog').toggleClass('hide');
            } else {
                platform.showTip('edit');
            }
        };
        self.fnView = function () {//查看操作
            var selections = self.tableViewModel.getSelections();
            if (selections.length === 1) {
                var id = selections[0].org_id;
                self.orgViewModel.showViewForm(id);
                $('#orgDialog').toggleClass('hide');
            } else {
                platform.showTip('VIEW');
            }
        };
        self.fnRemove = function () {//删除操作
            var selections = self.tableViewModel.getSelections();
            if (selections.length === 1) {
                bootbox.confirm({
                    title: '<i class="fa fa-warning"></i>&nbsp;&nbsp;删除提示信息',
                    size: 'small',
                    message: '删除存在子节点的数据时，将删除全部该节点下的数据，确认是否删除?',
                    buttons: {
                        confirm: {
                            label: '确认',
                            className: 'btn-success btn-sm'
                        },
                        cancel: {
                            label: '取消',
                            className: 'btn-default btn-sm'
                        }
                    },
                    callback: function () {
                        var id = selections[0].org_id;
                        rest.remove(id);
                    }
                });
            } else {
                platform.showTip('remove');
            }
        };
        self.refreshTree = function () {
            var nodes = rest.loadTreeNodes();
            self.treeViewModel.refresh(nodes);
        };
        self.fnMove = function () {

        };
        return self;
    };
    var viewModel = new ViewModel();
    return viewModel;
});